package com.yupi.springbootinit.bizmq;

import com.rabbitmq.client.Channel;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.manager.AiManager;
import com.yupi.springbootinit.model.entity.Chart;
import com.yupi.springbootinit.service.ChartService;
import com.yupi.springbootinit.service.UserService;
import com.yupi.springbootinit.utils.ExcelUtils;
import com.yupi.springbootinit.ws.ChatEndpoint;
import com.yupi.springbootinit.ws.WebSocketToUser;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Slf4j
public class BiMessageConsumer {

    @Resource
    private WebSocketToUser webSocketToUser;
    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private ChartService chartService;

    @Resource
    private UserService userService;

    @Resource
    private AiManager aiManager;

    //指定程序监听的消息队列
    @SneakyThrows
    @RabbitListener(queues = {BiMqConstant.BI_QUEUE_NAME},ackMode="MANUAL")
    public void receiveMessage(String message, Channel channel,@Header(AmqpHeaders.DELIVERY_TAG) long deliverTag){

        if(StringUtils.isBlank(message)){
            channel.basicNack(deliverTag,false,false);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"消息为空");
        }

        long chartId=Long.parseLong(message);
        Chart chart=chartService.getById(chartId);
        if(chart==null){
            channel.basicNack(deliverTag,false,false);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"查无此表");
        }

        Chart updateChart=new Chart();
        updateChart.setId(chart.getId());
        updateChart.setStatus("running");
        boolean b=chartService.updateById(updateChart);
        if(!b){
            channel.basicNack(deliverTag,false,false);
            handleChartUpdateError(chart.getId(),"图表状态更改失败");
        }
        //调用ai
        String result=aiManager.doChat(1799479915975483393L,buildUserInput(chart));
        String[] splits=result.split("【【【");
        if(splits.length<3){
            handleChartUpdateError(chart.getId(),"AI生成失败");
        }
        String genChart=splits[1];
        String genResult=splits[2];
        Chart updateChartTwice=new Chart();
        updateChartTwice.setId(chart.getId());
        updateChartTwice.setGenChart(genChart);
        updateChartTwice.setGenResult(genResult);
        updateChartTwice.setStatus("succeed");

        webSocketToUser.sendToUser("图表生成成功",String.valueOf(updateChart.getUserId()));
        log.info("终于conggongl");
        boolean b1=chartService.updateById(updateChartTwice);
        if(!b1){
            channel.basicNack(deliverTag,false,false);
            handleChartUpdateError(chart.getId(),"更新图表成功状态失败");
            return;
        }

        log.info("receiveMessage message = {}",message);
        channel.basicAck(deliverTag,false);
    }

    private String buildUserInput(Chart chart){
        String csvData=chart.getChartData();

        StringBuilder userInput=new StringBuilder();
        userInput.append("分析需求：").append("\n");
        String useGoal=chart.getGoal();
        if(StringUtils.isNotBlank(chart.getChartType())){
            useGoal+="，请使用"+chart.getChartType();
        }
        userInput.append(useGoal).append("\n");
        userInput.append("原始数据：").append("\n");
        userInput.append(csvData).append("\n");
        return userInput.toString();
    }

    private void handleChartUpdateError(long chartId,String execMessage){
        Chart updateChartResult=new Chart();
        updateChartResult.setId(chartId);
        updateChartResult.setStatus("failed");
        updateChartResult.setExecMessage(execMessage);
        boolean updateResult=chartService.updateById(updateChartResult);
        if(!updateResult){
            log.error("更图表失败状态失败"+chartId);
        }
    }

}
